﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Example.Base.Interfaces.Services;
using Example.Base.Interfaces.Repositories;
using Ninject;
using Example.Base.Entities;
using Example.Base;

namespace Example.Data.Services
{
    public class AuthenticateService : IAuthenticateService
    {
        [Inject]
        public IRepository<User> UserRepository { get; set; }
        
        private IAuthenticateTicket _ticket;

        public bool Authenticate(string login, string password)
        {
            return Authenticate(login, password, new TimeSpan(1, 0, 0));
        }
        public bool Authenticate(string login, string password, TimeSpan expiryPeriod)
        {
            try
            {
                var user =
                    UserRepository.Get(u => u.Login.Equals(login) && u.Password.Equals(password)).FirstOrDefault();

                if (user != null)
                {
                    _ticket = new AuthenticateTicket { User = user, SignInDateTime = DateTime.Now, ExpiryPeriod = expiryPeriod };
                }

                if (_ticket != null)
                {
                    if (OnSuccess != null)
                        OnSuccess(this, new AuthenticateEventArgs { Ticket = _ticket });

                    return true;
                }
                else
                {
                    if (OnFail != null)
                        OnFail(this, EventArgs.Empty);

                    return false;
                }
            }
            catch (Exception ex)
            {
                if (OnFail != null)
                    OnFail(null, EventArgs.Empty);

                return false;
            }
        }

        public event EventHandler<AuthenticateEventArgs> OnSuccess;
        public event EventHandler OnFail;        
    }
}
